declare namespace pm = "http://www.politicalmashup.nl";

let $members := collection('/db/projdb/ge-2009')/root/pm:proceedings/pm:topic/pm:stage-direction/pm:members/pm:person

let $speakers := distinct-values( 
    for $m in $members
        return data($m/@pm:speaker)
)

let $outputByClusters := document('/db/projdb/clusterdata.xml')/clusters/cluster

let $outputBySpeakers := element speakers {
    for $speaker in $speakers
        return element speaker {
            element name {
                data($speaker)
            },
            element clusters {
                for $cluster in $outputByClusters
                where ( exists( $cluster/labels/label/t/s[text() = data($speaker)] ) )
                    return element cluster {
                        element fullLabel {
                            data($cluster/fullLabel)
                        },
                        for $currentLabel in $cluster/labels/label
                        where ( exists( $currentLabel/t/s[text() = data($speaker)] ) )
                            return element label {
                                element name {
                                    data($currentLabel/name)
                                },
                                element topics {
                                    for $currentTopic in $currentLabel/t
                                    where( exists( $currentTopic/s[text() = data($speaker)] ) )
                                        return element topic {
                                            data($currentTopic/id)
                                        }
                                }
                        }
                    }
            }
        }       
}

let $collection := 'xmldb:exist:///db/projdb'
let $file-name := 'clusterdataSortedBySpeakers.xml'

let $store-return-status := xmldb:store($collection, $file-name, $outputBySpeakers )

return <message>New Document Created {$store-return-status} at {$collection}/{$file-name}</message>